<?PHP
session_start();
include("common/connect.php");
include("common/common.php");

if( !isset($_SESSION["user"]) ) 
{
	$url = "Location:login.php?ref=deal_trade.php";
	header($url);
}

$id = CheckUrlParamNoDie("id");
$opt = CheckUrlParamNoDie("opt");
$tbid = CheckUrlParamNoDie("tbid");
$opter = CheckUrlParamNoDie("opter");
$tradeid = CheckUrlParamNoDie("tradeid");
$tradeid_begin = substr($tradeid, 0, 6);
$tradeid_end = substr($tradeid, -4);
if (trim($tradeid)=="" || $tradeid_begin=="" or $tradeid_end=="")
{
	echo "<script>alert('严重错误！订单号不能为空，请立即找冰峰！');</script>";
	exit;
}
$phone = "";
$userid="";
$info = "";
$userid="";

//echo $opt;
if ($opt == "giveup")
{
	if ($userid == "")
		mysql_query( "update report_items set handle_code=0,operater='' where trade_id like '".$tradeid_begin."%".$tradeid_end."'");
	else
		mysql_query( "update report_items set handle_code=0,operater='' where outer_code='$userid'");
//	echo "update report_items set handle_code=0 where trade_id like '".$tradeid_begin."%".$tradeid_end;
	if (mysql_affected_rows() == 0)
		echo "<script>alert('出错了，请找程序员。');</script>";
	else
		echo "<script>window.history.go(-2);</script>";

	exit;
}
else if ($opt == "marklost")
{
	mysql_query( "update report_items set handle_code=3,operater='".$_SESSION["user"]."' where trade_id like '".$tradeid_begin."%".$tradeid_end."'");
	if (mysql_affected_rows() == 0)
		echo "<script>alert('标志为丢单出错了，请找程序员。');</script>";
	else
		echo "<script>window.history.go(-2);</script>";

	exit;
}

// 如果目标账号为空，要去查查
if ($tbid == "null")	// 统一一下
	$tbid = "";
if ($tbid == "")
{
	$result = mysql_query( "select tb_id from trade where trade_id like '".$tradeid_begin."%".$tradeid_end."' limit 1" );
	//echo "select tb_id from trade where trade_id like '".$tradeid_begin."%".$tradeid_end."' limit 1 <br>";
    if ($result)
    {
		$row = mysql_fetch_assoc( $result );
		$tbid = $row["tb_id"];
	}
	
	if ($tbid == "")
	{
		#echo "select tb_id from feedback where item_url like '".$tradeid_begin."%".$tradeid_end."' limit 1";
		$result = mysql_query( "select tb_id from feedback where item_url like '".$tradeid_begin."%".$tradeid_end."' limit 1" );
    	if ($result)
    	{
			$row = mysql_fetch_assoc( $result );
			$tbid = $row["tb_id"];
		}
	}
}
else if (strlen($tbid) < 6)	// id
{
	$result = mysql_query( "select tb_id from user where id=$tbid limit 1" );
    if (mysql_num_rows($result) > 0)
    {
		$userid = $tbid;
		$row = mysql_fetch_assoc( $result );
		$tbid = $row["tb_id"];
	}
}

//
if ($opt == "getphone")
	$tbid = trim(GetPostParamStr("tb"));

// 取Phone和userid
if ($tbid)
{
	$result = mysql_query( "select id,phone from user where tb_id='" .$tbid. "' limit 1" );
    if ($result)
    {
		$row = mysql_fetch_assoc( $result );
		$phone = $row["phone"];
		$userid = $row["id"];
	}
}
	
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
<!--
body,td,th {
	font-family: 宋体;
	font-size: 13px;
	color: #000;
}
body {
	background-color: #FFF;
}
-->
</style>

<script language="javascript" src="js/common.js"></script>
<script language="javascript">
function OnBtn(strAction)
{
	var tbid = document.getElementById("tb_id").value;
	var phone = document.getElementById("phone_id").value;
	
	if( tbid == "" || ((!isemail( tbid )) && (!isphone( tbid ))) )
	{
		alert( "用户支付宝帐号输入有误！" );
		document.getElementById("tb_id").focus();
		return;
	}
	
	document.getElementById("form1").action = strAction + "&id=<?PHP echo $id; ?>&tbid=<?PHP echo $tbid; ?>&tradeid=<?PHP echo $tradeid; ?>";
	document.getElementById("form1").submit();
}
</script>

<?php

//echo $t[1];
//exit;

if ($opt == "")
{
	if ($userid == "")
		$sql = "update report_items set handle_code = 1,operater='".$_SESSION["user"]."' where handle_code = 0 and (id=".$id." or trade_id like '".$tradeid_begin."%".$tradeid_end."')";
	else
		$sql = "update report_items set handle_code = 1,operater='".$_SESSION["user"]."' where handle_code = 0 and (id=$id or outer_code='$userid')";
		
	$result = mysql_query( $sql );
	if (mysql_affected_rows() == 0)
	{
		echo "<script>alert('已经有人在处理了哦，呵呵');window.history.back();</script>";
		//exit;
	}
}
else if ($opt == "savein" || $opt == "savein_ok")
{
	$bInOK = 0;
	if ($opt == "savein_ok")
		$bInOK = 1;

	$tbid = trim(GetPostParamStr("tb"));
	$phone = trim(GetPostParamStr("phone"));
	$info = trim(GetPostParamStr("info"));
	$ex1yuan = trim(GetPostParamStr("ex1yuan"));
	
//	if (0){
	$allCommission = 0;
	$srcIds = explode(',', GetPostParamStr("srcIds"));
	for($i=0; $i < count($srcIds) - 1; $i++)
	{
		if ($i == 0)	// 只在第一条加1元标志，方便统计
			$allCommission += _DealItemSrc($bInOK, $srcIds[$i], $userid, $tbid, $phone, $info, $ex1yuan);
		else
			$allCommission += _DealItemSrc($bInOK, $srcIds[$i], $userid, $tbid, $phone, $info, 0);
	
		// 更新源表
		$sql = "update report_items set handle_code = 2,operater='".$_SESSION["user"]."' where id=".$srcIds[$i]." and handle_code = 1 limit 1";
		$result = mysql_query( $sql );
		if (mysql_affected_rows() == 0)
		{
			echo "<script>alert('更新源表状态到2时出错！');window.history.back();</script>";
			exit;
		}
	}
	// 消息	// 返利狂欢，双倍兔币，简单定一个期间吧
	mysql_query( "insert into gwt_msg (touser,content) values ($userid, '您在购物兔成功购物获得返现，本次赠送您 ".(round($allCommission*10, 0))." 兔币。')" );
//	mysql_query( "insert into gwt_msg (touser,content) values ($userid, '您在购物兔成功购物获得返现，年底返利狂欢，兔币双倍！本次赠送您 ".(2*round($allCommission*10, 0))." 兔币。')" );
	if ($bInOK && $ex1yuan)		// 标志入库的时候才需要发消息
		mysql_query( "insert into gwt_msg (touser,content) values ($userid, '您在购物兔首次成功购物，额外赠送您 1 元')" );
	
//	}
	
	//
	$desIds = explode(',', GetPostParamStr("desIds"));
	for($i=0; $i < count($desIds) - 1; $i++)
	{
		_DealItemDes($bInOK, $desIds[$i], $tbid, $phone, $info);
	}
	
	// 标志上报项
	mysql_query( "update trade set has_return=1,opt_time=now(),operater='".$_SESSION["user"]."' where trade_id like '".$tradeid_begin."%".$tradeid_end."'" );
	mysql_query( "update feedback set state=1,opt_time=now(),operater='".$_SESSION["user"]."' where item_url like '".$tradeid_begin."%".$tradeid_end."'" );

	echo "<script>alert('处理成功！');window.history.go(-2);</script>";
//	echo "<script>alert('处理成功！');/script>";
	exit;
}

function _DealItemSrc( $bInOK, $id, $userid, $tbid, $phone, $info, $ex1yuan)
{
	$user = $_SESSION["user"];
	$zfb = "";
	$result = mysql_query( "select * from report_items where id=" . $id . " and handle_code = 1 limit 1" );
    if ($result)
    {
		$row = mysql_fetch_assoc( $result );
		$sql = "insert into order_handle_report (user_id,
		app_key, outer_code, trade_id, pay_time, pay_price,real_pay_fee,item_title, item_num, shop_title, 
		commission_rate, commission, num_iid, seller_nick, 
		phone, tbid, info, 
		handle_code, operater, a_no, ex1yuan) 
		values ($userid,
		'".$row["app_key"]."','".$row["outer_code"]."','".$row["trade_id"]."','".$row["pay_time"]."',
		'".$row["pay_price"]."','".$row["real_pay_fee"]."','".$row["item_title"]."','".$row["item_num"]."','".$row["shop_title"]."',
		'".$row["commission_rate"]."','".$row["commission"]."','".$row["num_iid"]."','".$row["seller_nick"]."',
		'".$phone."','".$tbid."','".$info."',".$bInOK.",'".$_SESSION["user"]."',".$row["a_no"].",$ex1yuan)";
		$result2 = mysql_query( $sql );
		if (mysql_affected_rows() == 0)
		{
			echo "<script>alert('处理过程中发生失败，请告诉程序员，出错代码：1');window.history.back();</script>";
			exit;
		}
		
		// 操作日志
		mysql_query( "insert into opt_log (`sql`, user, zfb) values ('".mysql_real_escape_string($sql)."', '$user', '$zfb')" );
		
		// 加兔币
		$addlevel = $row["commission"]*0.6*10;
//		$addlevel = $row["commission"]*0.6*10*2;	// 返利狂欢，兔币双倍
		mysql_query( "update user set level=level+$addlevel,tubi=tubi+$addlevel where id=$userid" );
		$_res = mysql_query( "select commend_id,all_fx from user where id=$userid" );
		$_row = mysql_fetch_assoc( $_res );
		if ($_row["commend_id"] != "" && is_numeric($_row["commend_id"]) && $_row["all_fx"] == 0)	// 有上线用户并且是第一次购物
		{
			mysql_query( "update user set level=level+100,tubi=tubi+100 where id=".$_row["commend_id"] );
			mysql_query( "insert into gwt_msg (touser,content) values (".$_row["commend_id"].",'您邀请的好友（".substr($tbid, 0, 5)."***）在购物兔成功购物啦，现赠送您 100 兔币，再接再厉哦。')" );
		}
		
		// 一共返了多少
		mysql_query( "update user set all_fx=all_fx+".round($row["commission"]*0.6, 2)." where id=$userid" );
		
		return $row["commission"]*0.6;
    }
	else
	{
		echo "<script>alert('处理过程中发生失败，请告诉程序员，出错代码：2');window.history.back();</script>";
		exit;
	}
	
	return 0;
}

function _DealItemDes( $bInOK, $id, $tbid, $phone, $info)
{	
	$sql = "update order_handle_report set handle_code=".$bInOK." where id=".$id;
//	echo $sql;
		
	$result2 = mysql_query( $sql );
	//if (mysql_affected_rows() == 0)	// 是有可能的
	//{
	//	echo "<script>alert('处理过程中发生失败！');window.history.back();/script>";
	//	exit;
	//}
}
?>
</head>

<body>
<br />

<table cellpadding="0" cellspacing="0" border="1" align="center">
	<tr>
    	<td height="25" width="50" align="center">序列号</td>
        <td width="200" align="center">时间</td>
        <td width="158" align="center">支付宝帐号</td>
      	<td width="198" align="center">订单号</td>
        <td width="198" align="center">商品Id</td>
        <td width="70" 	align="center">交易额</td>
        <td width="144" align="center">佣金额*0.6</td>
        <td width="143" align="center">操作员</td>
        <td width="143" align="center">说明</td>
    </tr>
<tr><td colspan="7" align="center">--------同一订单号------------</td></tr>

<?PHP
$fNeedBackMoney = 0.0;
$srcIds = "";		// 源表的Id
$desIds = "";		// 目标表的Id
$strTradeIds = "购物兔返款，如果是促销产品，实际返现会稍少一些，本次返款订单列表如下：";	// 本次交易订单号列表

//$sql = "select * from report_items where handle_code = 1 and (id =".$id." or trade_id like '".$tradeid_begin."%".$tradeid_end."') order by id desc";
$sql = "select * from report_items where handle_code = 1 and (id =$id or outer_code='$userid') order by id desc";
//echo $sql;
//exit;
$result = mysql_query( $sql );
while( $result && $row = mysql_fetch_assoc( $result ))
{
	$fNeedBackMoney += $row["commission"];
	$srcIds .= $row["id"] . ",";
	$strTradeIds .= $row["trade_id"].", ￥".round($row["commission"]*0.6, 2)."; ";
?>
<tr>
    <td height="25" width="50" align="center"><?PHP echo $row["id"]; ?></td>
    <td width="200" align="center" title="<?PHP echo "操作时间：".$row["opt_time"]; ?>"><?PHP echo $row["pay_time"]; ?></td>
	<td width="198" align="center" title="<?PHP echo $userid; ?>"><?PHP echo $tbid; ?>&nbsp;</td>
	<td width="70" 	align="center" title="<?PHP echo $row["item_num"]."件"; ?>"><?PHP echo $row["trade_id"]; ?>&nbsp;</td>
    <td width="70" 	align="center" title="<?PHP echo $row["item_title"]; ?>"><?PHP echo $row["num_iid"]; ?>&nbsp;</td>
	<td width="144" align="center" title="<?PHP echo $row["real_pay_fee"]; ?>"><?PHP echo $row["pay_price"]; ?>&nbsp;</td>
	<td width="158" align="center" title="<?PHP echo ($row["commission_rate"] * 100)."%"; ?>"><?PHP echo round($row["commission"] *0.6, 2); ?>&nbsp;</td>
	<td width="143" align="center"><?PHP echo $row["operater"]; ?></td>
    <td width="143" align="center">&nbsp;</td>
</tr>
<?PHP
}
?>
<tr><td colspan="7" align="center">-------之前未返的-------------</td></tr>
<?PHP
// 之前未返现的
$sql = "select * from order_handle_report where handle_code = 0 and tbid ='".$tbid."' order by id desc";
$result = mysql_query( $sql );
while( $result && $row = mysql_fetch_assoc( $result ))
{
	$fNeedBackMoney += $row["commission"];
	$desIds .= $row["id"] . ",";
	$strTradeIds .= $row["trade_id"].", ￥".round($row["commission"]*0.6, 2)."; ";
?>
<tr>
    <td height="25" width="50" align="center"><?PHP echo $row["id"]; ?></td>
    <td width="200" align="center" title="<?PHP echo "操作时间：".$row["opt_time"]; ?>"><?PHP echo $row["pay_time"]; ?></td>
	<td width="198" align="center" title="<?PHP echo $userid; ?>"><?PHP echo $row["tbid"]; ?>&nbsp;</td>
	<td width="70" 	align="center"><?PHP echo $row["trade_id"]; ?>&nbsp;</td>
    <td width="70" 	align="center" title="<?PHP echo $row["item_title"]; ?>"><?PHP echo $row["num_iid"]; ?>&nbsp;</td>
	<td width="144" align="center"><?PHP echo $row["pay_price"]; ?>&nbsp;</td>
	<td width="158" align="center"><?PHP echo $row["commission"]; ?>&nbsp;</td>
    <td width="143" align="center"><?PHP echo $row["operater"]; ?></td>
    <td width="143" align="center"><?PHP echo $row["info"]; ?></td>
</tr>
<?PHP
}
?>
</table>


<hr />
<form method="post" id="form1" name="form1" >
<table cellpadding="0" cellspacing="0" border="1" align="center">
    <tr>
   	  <td width="60" height="30" align="center">账号：</td>
      <td width="140" height="22"><input type="text" width="140" id="tb_id" name="tb" height="20" value="<?PHP echo $tbid; ?>" onclick="javascript:select();" /></td>
      <td height="30"> 手机号： 
        <input type="text" width="140" id="phone_id" name="phone" height="20" value="<?PHP echo $phone; ?>" onclick="javascript:select();" /><input type="button" name="btnin" value="更新数据" onclick="javascript:OnBtn('deal_trade.php?opt=getphone');" <?PHP if ($tbid != "") echo "disabled='disabled'"; ?> />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <?PHP 
		$hasReturn = mysql_result(mysql_query("select sum(commission)*0.6 as tmp from order_handle_report where handle_code=1 and tbid='".$tbid."'"), 0, "tmp");
		$fNeedBackMoney = round($fNeedBackMoney * 0.6, 2);
		$bNeedExt1Yuan = $hasReturn ==0.0 && $fNeedBackMoney < 1.0;
		if ($bNeedExt1Yuan)		// 第一次返现而且总额少于1元
		{
			if (mb_strlen($strTradeIds,'utf8') > 170)
			{
				$strTradeIds = mb_substr($strTradeIds,0,170,'UTF-8');
				$strTradeIds = strrev($strTradeIds);
				$strTradeIds = substr($strTradeIds, strpos($strTradeIds, ";"));
				$strTradeIds = strrev($strTradeIds);
				$strTradeIds .= " 等，第一次购物额外赠送1元，详情请参见个人中心。"; 
			}
			else
				$strTradeIds .= "第一次购物额外赠送1元，详情请参见个人中心。"; 
				
			$fNeedBackMoney += 1.0;
		}
		else
		{
			if (mb_strlen($strTradeIds,'utf8') > 185)
			{
				$strTradeIds = mb_substr($strTradeIds,0,185,'UTF-8');
				$strTradeIds = strrev($strTradeIds);
				$strTradeIds = substr($strTradeIds, strpos($strTradeIds, ";"));
				$strTradeIds = strrev($strTradeIds);
				$strTradeIds .= " 等，详情请参见个人中心。"; 
			}
			else
				$strTradeIds .= "详情请参见个人中心。"; 		
		}
			
		$_data = ($tbid."|".$phone."|".$fNeedBackMoney."|购物兔返款，欢迎推荐给好友~|".$strTradeIds); 
//		$_data = ($tbid."|".$phone."|".$fNeedBackMoney."|购物兔返款，返利狂欢，礼物多多，欢迎关注|".$strTradeIds); 
		?>
<a href="http://_my_data_transport_/?<?PHP echo $_data; ?>" target="_blank">去返款</a>
        </td>
    </tr>
    <tr>
    	<td colspan="2" height="30" align="right">共需返还金额：</td>
        <td><input type="text"  width="340" id="all_return_id" name="all_return" height="20" value="<?PHP echo $fNeedBackMoney; ?>" />&nbsp;</td>
    </tr>
    <tr>
    	<td colspan="2" height="30" align="right"s>备注：</td>
        <td><textarea name="info" cols="56" rows="7"><?PHP echo $info; ?></textarea></td>
    </tr>
    <tr>
    	<td colspan="3" height="30" align="center">
        <input type="hidden" name="srcIds" value="<?PHP echo $srcIds; ?>" />
		<input type="hidden" name="desIds" value="<?PHP echo $desIds; ?>" />
        <input type="hidden" name="ex1yuan" value="<?PHP if ($bNeedExt1Yuan) echo "1"; else echo "0"; ?>" />
        <input type="button" name="btnin" value="入库" onclick="javascript:OnBtn('deal_trade.php?opt=savein');"/>&nbsp;&nbsp;
        <input type="button" name="btnin_ok" value="入库并标志返现" onclick="javascript:OnBtn('deal_trade.php?opt=savein_ok');"/>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <a href="deal_trade.php?opt=giveup&tradeid=<?PHP echo $tradeid; ?>">放弃处理</a>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <a href="deal_trade.php?opt=marklost&tradeid=<?PHP echo $tradeid; ?>">标志为丢单</a>
        </td>
    </tr>
</table>
</form>

<div align="center">
<input type="text" width="180" height="20" value="购物兔返款，欢迎推荐给好友" onclick="javascript:select();" />
<input type="text" width="180" height="20" value="<?PHP echo $strTradeIds; ?>" onclick="javascript:select();" />
<?PHP 
echo "此用户共返了 ".$hasReturn."元";
?>

</div>

</body>
</html>